import router, { resetRouter } from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import Message from '@/components/Message/index.js'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login']

// 全局路由守卫，验证用户是否登录
router.beforeEach(async(to, from, next) => {
  NProgress.start()

  if (getToken()) {
    // 拥有Token 不需要再登陆
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      // 查看是否有角色信息
      if (store.getters.asyncRoutes instanceof Array && store.getters.asyncRoutes.length > 0) {
        next()
      } else {
        try {
          const { user_permissions } = await store.dispatch('user/getInfo')
          resetRouter()
          const routes = await store.dispatch('permission/generateRoutes', user_permissions)
          routes.forEach(route => {
            router.addRoute(route) // 动态添加可访问路由表
          })
          next({ ...to, replace: true })
        } catch (error) {
          await store.dispatch('user/resetToken')
          Message.error(error)
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // 注意下面的if/else，如果只写 next('/login')，将一直跳转/login,导致堆栈溢出
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
    NProgress.done()
  }
})

router.afterEach(() => {
  NProgress.done()
})
